/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-24，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.chinamobile.ln.ictenterprises.R;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.Constants;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;
import com.chinamobile.ln.ictenterprises.model.ChooseContact;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.model.request.SendMsg;
import com.chinamobile.ln.ictenterprises.model.request.Version;
import com.chinamobile.ln.ictenterprises.model.request.SendMsg.DestPhone;
import com.chinamobile.ln.ictenterprises.model.response.ResponseSendMsg;
import com.chinamobile.ln.ictenterprises.model.response.ResponseVersion;
import com.chinamobile.ln.ictenterprises.utils.AlertDialogUtil;
import com.chinamobile.ln.ictenterprises.utils.JsonUtil;
import com.chinamobile.ln.ictenterprises.utils.NetUtil;
import com.chinamobile.ln.ictenterprises.utils.StringUtil;
import com.chinamobile.ln.ictenterprises.utils.Utils;
import com.chinamobile.ln.ictenterprises.utils.ValidateUtil;
import com.chinamobile.ln.ictenterprises.widget.DateTimePickDialogUtil;
import com.cmccitcenter.downloaddemo.UpdateManager;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class SendMsgActivity extends ParentActivity implements OnClickListener
{
    private CheckBox send_timer_check, is_long_msg_check;
    private TextView send_time_txt, idiograph_txt, long_num_txt, msg_num_txt;
    private RelativeLayout send_btn, ly_guide;
    private EditText et_msg_content, contact_txt;
    private ImageView add_contact_btn;
    /** 选择联系人请求 */
    private static final int SELECT_CONTACTS = 1;
    private String downLoadUrl;
    private List<DestPhone> list = null;
    /** 中文输入60字/条 */
    private int chineseCount = 60;
    /** 英文输入140字/条 */
    private int englishCount = 140;
    /** 已选择的联系人 **/
    private Map<String, ChooseContact> chooseMap = new HashMap<String, ChooseContact>();
    /** 最终的收件人 **/
    private Map<String, ChooseContact> endChooseMap;

    private List<ChooseContact> chooseContacts = new ArrayList<ChooseContact>();
    private ImageView guideImageView;
    /**升级管理器*/
    private UpdateManager mUpdateManager;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.send_msg_layout);
        sharedPref = getSharedPreferences("firststart", Context.MODE_PRIVATE);
        aotuUpdate();
        checkUpdate();
    }

    @Override
    protected void setupView()
    {
        if (sharedPref.getBoolean("menufirststart", true))
        {
            Editor editor = sharedPref.edit();
            editor.putBoolean("menufirststart", false);
            editor.commit();
            ly_guide = (RelativeLayout) findViewById(R.id.ly_guide);
            ly_guide.setVisibility(View.VISIBLE);
            ly_guide.getBackground().setAlpha(100);
            guideImageView = (ImageView) findViewById(R.id.ok);
            guideImageView.setOnClickListener(this);
        }
        TextView topTitleView = (TextView) findViewById(R.id.tv_top_title);
        topTitleView.setText(R.string.sendMsg);
        send_time_txt = (TextView) findViewById(R.id.send_timer_txt);
        idiograph_txt = (TextView) findViewById(R.id.idiograph_txt);
        contact_txt = (EditText) findViewById(R.id.contact_txt);
        long_num_txt = (TextView) findViewById(R.id.long_num_txt);
        msg_num_txt = (TextView) findViewById(R.id.msg_num_txt);
        add_contact_btn = (ImageView) findViewById(R.id.choose_contact_btn);
        add_contact_btn.setOnClickListener(this);
        long_num_txt.setText("0");
        msg_num_txt.setText("0");
        send_btn = (RelativeLayout) findViewById(R.id.send_btn);
        send_btn.setOnClickListener(this);
        et_msg_content = (EditText) findViewById(R.id.msg_content);
        et_msg_content.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                int count)
            {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                int after)
            {

            }

            @Override
            public void afterTextChanged(Editable s)
            {
                int msgNum = 0;
                int length = s.length();
                long_num_txt.setText(String.valueOf(length));
                if (length > 0)
                {
                    // 如果输入中文
                    if (StringUtil.hasChinese(s.toString()))
                    {
                        if ((length % chineseCount) == 0)
                        {
                            msgNum = length / chineseCount;
                        }
                        else
                        {
                            msgNum = length / chineseCount + 1;
                        }
                    }
                    // 如果输入英文
                    else
                    {
                        if ((length % englishCount) == 0)
                        {
                            msgNum = length / englishCount;
                        }
                        else
                        {
                            msgNum = length / englishCount + 1;
                        }
                    }
                }
                else
                {
                    msgNum = 0;
                }
                msg_num_txt.setText(String.valueOf(msgNum));
            }
        });
        send_btn.setOnClickListener(this);
        idiograph_txt.setText(sharedPref.getString(Constants.SMS_SIGN, null));
        send_timer_check = (CheckBox) findViewById(R.id.send_timer_check);
        send_timer_check
            .setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked)
                {
                    if (isChecked)
                    {
                        DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                            SendMsgActivity.this, StringUtil
                                .getNowDate("yyyy年MM月dd日 HH:mm"));
                        dateTimePicKDialog.dateTimePicKDialog(send_time_txt,
                            send_timer_check);
                    }
                    else
                    {
                        send_time_txt.setText(null);
                    }
                }
            });
        is_long_msg_check = (CheckBox) findViewById(R.id.is_long_msg);
        btnMenu = (LinearLayout) findViewById(R.id.btn_top_menu);
        btnMenu.setOnClickListener(this);
    }
    


    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
        case R.id.btn_top_menu:
            if (!app.getMenu().isShown())
            {
                app.getMenu().showContent();
            }
            else
            {
                app.getMenu().showMenu();
            }
            break;
        case R.id.choose_contact_btn:
            String contact = contact_txt.getText().toString();
            if (StringUtil.isMobileNum11(contact))
            {
                contact_txt.setText(null);
                addEditTextName(contact);
            }
            if (contact.length() > 0)
            {
                if (!checkContact())
                    return;
            }
            Intent intent = new Intent();
            intent.setClass(SendMsgActivity.this, ChooseContactActivity.class);
            startActivityForResult(intent, SELECT_CONTACTS);
            break;
        case R.id.send_btn:
            sendMsg();
            break;
        case R.id.ok:
            ly_guide.setVisibility(View.GONE);
            break;
        }
    }

    /**
     * 显示添加联系人
     * @param mTextName
     */
    private void addEditTextName(String mTextName)
    {
        TextView mTextView = new TextView(this);
        mTextView.setText(mTextName);
        mTextView.setPadding(6, 4, 6, 4);
        mTextView.setTextSize(14);
        mTextView.setGravity(Gravity.CENTER);
        // mTextView.setBackgroundColor(getResources().getColor(R.color.blue));
        mTextView.setTextColor(getResources().getColor(R.color.blue));
        mTextView.setDrawingCacheEnabled(true);
        mTextView.measure(
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        mTextView.layout(0, 0, mTextView.getMeasuredWidth(),
            mTextView.getMeasuredHeight());
        Bitmap newBitmap = mTextView.getDrawingCache();// TextView转换为Bitmap
        // 使用ImageSpan
        ImageSpan imageSpan = new ImageSpan(this, newBitmap);
        SpannableString spannableString = new SpannableString(mTextName);
        spannableString.setSpan(imageSpan, 0, mTextName.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);// 把固定字符串转换为imagespan
        contact_txt.append(spannableString);// 添加到EditText中
        contact_txt.append("、");
    }

    /**
     * 发送短信
     */
    private void sendMsg()
    {
        if (ValidateUtil.isEmpty(contact_txt.getText().toString()))
        {
            showTip(R.string.contact_is_null);
            contact_txt.findFocus();
            return;
        }
        if (ValidateUtil.isEmpty(et_msg_content.getText().toString()))
        {
            showTip(R.string.msg_is_null);
            et_msg_content.findFocus();
            return;
        }
        // 最大不能超过5条短信。
        if (Integer.parseInt(msg_num_txt.getText().toString()) > 5)
        {
            showTip(R.string.msg_is_max);
            et_msg_content.findFocus();
            return;
        }
        String timing = send_time_txt.getText().toString();
        String isLongMsg = is_long_msg_check.isChecked() ? "1" : "0";
        String msg = et_msg_content.getText().toString();
        if (!checkContact())
            return;

        SendMsg sendMsg = new SendMsg(GlobalSetting.BATCH_SEND_SAMCNT, timing,
            isLongMsg, msg, list);
        String params = JsonUtil.objectToJson(sendMsg);
        Step step = Utils.paramsUtil(Config.SEND_MSG, params);
        HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
            HttpAsyncTask.CACHE_TYPE_ACTION, sharedPref.getString(
                Constants.COOKIES, ""), GlobalSetting.SEND_MSG);
        httpAsyncTask.setUIHandler(sendMsgHandler);
        mHttpManager.execute(httpAsyncTask);
        showProgressDialog("正在发送短信...");
    }

    /**
     * 检查联系人输入和选择
     */
    private boolean checkContact()
    {
        endChooseMap = new HashMap<String, ChooseContact>();
        String contacts = contact_txt.getText().toString();
        String[] str = new String[] {};
        // 选择地址本或者选择加输入
        // if (contacts.contains("、"))
        // {
        // str = contacts.split("、");
        // }
        // // 输入多个手机号码
        // else if (contacts.contains(","))
        // {
        // str = contacts.split(",");
        // }
        if (contacts.indexOf(",") > 0)
        {
            contacts = contacts.replaceAll(",", "、");
        }
        if (contacts.contains("、"))
        {
            str = contacts.split("、");
        }
        // 如果只输入一个手机号码
        else
        {
            if (StringUtil.isMobileNum11(contacts))
            {
                ChooseContact chooseContact = new ChooseContact("", contacts,
                    Constants.PHONE_TYPE);
                endChooseMap.put(contacts, chooseContact);
            }
            else
            {
                Toast.makeText(context, contacts + "为无效手机号码，请更正！",
                    Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        if (str.length > 20)
        {
            Toast.makeText(context, "收件人不能大于20个!", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (str.length > 0)
        {
            for (int i = 0; i < str.length; i++)
            {
                // 选择的地址本
                if (chooseMap.containsKey(str[i]))
                {
                    endChooseMap.put(str[i], chooseMap.get(str[i]));
                }
                else
                {
                    if (StringUtil.isMobileNum11(str[i]))
                    {
                        ChooseContact chooseContact = new ChooseContact("",
                            str[i], Constants.PHONE_TYPE);
                        // chooseMap.put(str[i], chooseContact);
                        endChooseMap.put(str[i], chooseContact);
                    }
                    else
                    {
                        String[] inputStr = str[i].split("、");
                        for (int j = 0; j < inputStr.length; j++)
                        {
                            if (StringUtil.isMobileNum11(inputStr[j]))
                            {
                                ChooseContact chooseContact = new ChooseContact(
                                    "", inputStr[j], Constants.PHONE_TYPE);
                                // chooseMap.put(inputStr[j], chooseContact);
                                endChooseMap.put(inputStr[j], chooseContact);
                            }
                            else
                            {
                                Toast.makeText(context,
                                    "无效手机号码：" + inputStr[j] + "，请更正！",
                                    Toast.LENGTH_SHORT).show();
                                return false;
                            }
                        }
                    }
                }
            }
        }
        list = new ArrayList<DestPhone>();
        for (String key : endChooseMap.keySet())
        {
            ChooseContact contact = endChooseMap.get(key);
            DestPhone destPhone = new DestPhone();
            destPhone.address = contact.address;
            destPhone.type = contact.type;
            list.add(destPhone);
        }
        return true;
    }

    private Handler sendMsgHandler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            dismissProgressDialog();
            if (msg.obj != null)
            {
                Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                int reultCode = (Integer) httpMap
                    .get(GlobalSetting.STUATUS_CODE);
                if (reultCode == GlobalSetting.STUATUS_CODE_SUCCESS)
                {
                    ResponseSendMsg responseSendMsg = (ResponseSendMsg) httpMap
                        .get(GlobalSetting.JSON_SEND_MSG);
                    if (responseSendMsg != null)
                    {
                        if (responseSendMsg.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_SUC))
                        {
                            String massage = responseSendMsg.results.sendResult;
                            Toast
                                .makeText(context, massage, Toast.LENGTH_SHORT)
                                .show();
                        }
                        else if (responseSendMsg.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_FAIL))
                        {
                            showTip(R.string.msg_send_fail);
                            return;
                        }
                    }
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_INVALIDATION)
                {
                    Intent intent = new Intent();
                    intent.setClass(SendMsgActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
                else if (reultCode == GlobalSetting.STUATUS_CODE_TIMEROUT)
                {
                    showTip(R.string.network_error);
                }
            }
            else
            {
                showTip(R.string.msg_send_fail);
                return;
            }
            contact_txt.setText(null);
            et_msg_content.setText(null);
            send_time_txt.setText(null);
            send_timer_check.setChecked(false);
            chooseMap.clear();
            chooseContacts.clear();
        };
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (requestCode)
        {
        case SELECT_CONTACTS:
            if (resultCode == Constants.RESULT_OK)
            {
                List<ChooseContact> list = data
                    .getParcelableArrayListExtra("dataList");
                chooseMap = new HashMap<String, ChooseContact>();
                if (list.size() > 0)
                {
                    for (ChooseContact cc : list)
                    {
                        chooseContacts.add(cc);
                        chooseMap.put(cc.name, cc);
                    }
                    /** 筛选输入框中的联系人 **/
                    List<String> cList = vailEditext();
                    if (cList.size() > 0)
                    {
                        for (String s : cList)
                        {
                            for (ChooseContact chooseContact : chooseContacts)
                            {
                                if (s.equals(chooseContact.name))
                                {
                                    chooseMap.put(chooseContact.name,
                                        chooseContact);
                                }
                                else if (StringUtil.isMobileNum11(s))
                                {
                                    ChooseContact cc = new ChooseContact("", s,
                                        Constants.PHONE_TYPE);
                                    chooseMap.put(s, cc);
                                }
                            }
                        }
                    }
                }
                chooseContact();
            }
            break;
        }
    }

    /**
     * 获取收件人输入框之中的值
     * @return
     */
    private List<String> vailEditext()
    {
        List<String> contactsNames = new ArrayList<String>();
        String contacts = contact_txt.getText().toString();
        String[] str = new String[] {};
        if (contacts.indexOf(",") > 0)
        {
            contacts = contacts.replaceAll(",", "、");
        }
        if (contacts.contains("、"))
        {
            str = contacts.split("、");
        }
        if (str.length > 0)
        {
            for (int i = 0; i < str.length; i++)
            {
                contactsNames.add(str[i]);
            }
        }
        return contactsNames;
    }

    /** 填充收件人 复合文本 **/
    private void chooseContact()
    {
        contact_txt.setText(null);
        for (String key : chooseMap.keySet())
        {
            addEditTextName(key);
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }
    
    /**
     * 自动升级
     */
    private void aotuUpdate()
    {
        mUpdateManager = new UpdateManager(SendMsgActivity.this);
        mUpdateManager.checkUpdateInfo(String.valueOf(getVersionCode()), "d93070bfc72ee5017f5134adf98cc506", "辽宁企信通", "0");
    }

    /** 检查更新 **/
    private void checkUpdate()
    {
        if (NetUtil.getNetType(this) != NetUtil.UNCONNECTED)
        {
            Version version = new Version(GlobalSetting.VERSION_UPDATE,
                getVersionName());
            String params = JsonUtil.objectToJson(version);
            Step step = Utils.paramsUtil(Config.VERSION, params);
            HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
                HttpAsyncTask.CACHE_TYPE_ACTION, "",
                GlobalSetting.UPDATE_VERSION);
            httpAsyncTask.setUIHandler(versionHandler);
            mHttpManager.execute(httpAsyncTask);
        }
    }

    private Handler versionHandler = new Handler() {
        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            if (msg.obj != null)
            {
                Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                int reultCode = (Integer) httpMap
                    .get(GlobalSetting.STUATUS_CODE);
                if (reultCode == GlobalSetting.STUATUS_CODE_SUCCESS)
                {
                    ResponseVersion responseVersion = (ResponseVersion) httpMap
                        .get(GlobalSetting.JSON_VERSION_UPDATE);
                    if (responseVersion != null)
                    {
                        if (responseVersion.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_SUC))
                        {
                            String versionName = responseVersion.results.versionName;
                            String fileSize = responseVersion.results.versionSize;
                            String versionCode = responseVersion.results.versionNum;
                            String isUpdate = responseVersion.results.isUpdate;
                            downLoadUrl = responseVersion.results.downloadUrl;
                            if (isUpdate.equals(GlobalSetting.UPDATE_YES))
                            {
                                String content = versionName + "\n大小："
                                    + fileSize + "M\n版本：" + "V" + versionCode;
                                showUpdateTip(content, true);
                            }
                        }
                    }
                }
            }
        };
    };

    /**
     * 下载提示
     */
    private void showUpdateTip(String content, boolean isUpdate)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("版本更新提示");
        builder.setMessage(content);

        if (isUpdate)
        {
            builder.setPositiveButton(R.string.download,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        Uri uri = Uri.parse(downLoadUrl);
                        Intent it = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(it);
                    }
                });
            builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.cancel();
                    }
                });
        }
        else
        {
            builder.setPositiveButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
        }
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        {
            AlertDialogUtil.exit(this, R.string.quit_title, R.string.quit_msg);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
